package com.sojpt.boot.controller.business;

import com.sojpt.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description: 本类用于
 * Created by JYN_LL on 2020/2/10 15:50
 */
@RestController
@RequestMapping(value = "/admin/file/")
public class LkyFileLoadAdminController{

    @Value("${file.uploadFolder}")   //总管理上传路径
    private String uploadFolder;
    

    /**
     * 实现总管理文件上传
     * */
    @PostMapping("fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file){
//        DicPopedom dicPopedom = new DicPopedom();
//        dicPopedom.setForwardAction("/file/fileUpload");
        if(file.isEmpty()){
            return "文件为空！";
        }
        String fileName = file.getOriginalFilename();

        int index = fileName.lastIndexOf(".");
        String fileType = fileName.substring(index+1,fileName.length());
        if(!(fileType.equals("docx") || fileType.equals("doc"))){
            return "文件格式错误！只支持docx和doc格式的word文档！";
        }
        int size = (int) file.getSize();
        //后天验证文件大小
        if(size>500*1024){
            return "文件太大";
        }

        File dest = new File(uploadFolder + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            out.write(file.getBytes());
            out.flush();
            out.close();
            // 进行数据的存储
            LkyDocumentTableManage lkyDocumentTableManage = new LkyDocumentTableManage();
            lkyDocumentTableManage.setId(UUID.randomUUID().toString().replace("-",""));
            lkyDocumentTableManage.setFileName(fileName);
            lkyDocumentTableManage.setAddress(uploadFolder);
            lkyDocumentTableManage.save();
//            dicPopedom.setPopedomName("上传"+fileName+"成功");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        }
    }

    /**
     * 实现学生文件上传
     * */
    @PostMapping("studentFileUpload")
    public String studentfileUpload(@RequestParam("file") MultipartFile file){
//        DicPopedom dicPopedom = new DicPopedom();
//        dicPopedom.setForwardAction("/file/fileUpload");
        if(file.isEmpty()){
            return "文件为空！";
        }
        String originalFilename = file.getOriginalFilename();

        int index = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(index+1,originalFilename.length());
        if(!(fileType.equals("docx") || fileType.equals("doc"))){
            return "文件格式错误！只支持docx和doc格式的word文档！";
        }
        int size = (int) file.getSize();
        //后天验证文件大小
        if(size>500*1024){
            return "文件太大";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = sdf.format(new Date());//服务器保存新文件名
        newFileName = newFileName + "." + fileType;//文件名+后缀名

        File dest = new File(uploadFolder + newFileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            out.write(file.getBytes());
            out.flush();
            out.close();
            // 进行数据的存储
            LkyTableStorage lkyTableStorage = new LkyTableStorage();
            String tsId = UUID.randomUUID().toString().replace("-","");
            lkyTableStorage.setId(tsId);
            lkyTableStorage.setFileName(originalFilename);  // 多个学生上传的是同样的文件  为保证不同命用时间戳命名
            lkyTableStorage.setAddress(uploadFolder);
            lkyTableStorage.setFileType(fileType);
            lkyTableStorage.setNewFileName(newFileName);
            lkyTableStorage.setCreationTime(new Date());
            lkyTableStorage.setUpdateDate(new Date());
            lkyTableStorage.save();

            // 保存学生填表记录
            LkyFillInFormRecord lkyFillInFormRecord = new LkyFillInFormRecord();
            String ffrId = UUID.randomUUID().toString().replace("-","");
            lkyFillInFormRecord.setId(ffrId);
            lkyFillInFormRecord.setStaute(1);  // 1表示已提交
            lkyFillInFormRecord.setTableStorageId(tsId);
            lkyFillInFormRecord.save();
//            dicPopedom.setPopedomName("上传"+fileName+"成功");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return tsId;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        }
    }

    /**
     * 实现老师文件上传
     * */
    @PostMapping("teacherFileUpload")
    public String teacherfileUpload(@RequestParam("file") MultipartFile file){
//        DicPopedom dicPopedom = new DicPopedom();
//        dicPopedom.setForwardAction("/file/fileUpload");
        if(file.isEmpty()){
            return "文件为空！";
        }
        String originalFilename = file.getOriginalFilename();

        int index = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(index+1,originalFilename.length());
        if(!(fileType.equals("docx") || fileType.equals("doc"))){
            return "文件格式错误！只支持docx和doc格式的word文档！";
        }
        int size = (int) file.getSize();
        //后天验证文件大小
        if(size>500*1024){
            return "文件太大";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = sdf.format(new Date());//服务器保存新文件名
        newFileName = newFileName + "." + fileType;//文件名+后缀名

        File dest = new File(uploadFolder + newFileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            out.write(file.getBytes());
            out.flush();
            out.close();
            // 进行数据的存储
            LkyTableStorage lkyTableStorage = new LkyTableStorage();
            String tsId = UUID.randomUUID().toString().replace("-","");
            lkyTableStorage.setId(tsId);
            lkyTableStorage.setFileName(originalFilename);  // 多个学生上传的是同样的文件  为保证不同命用时间戳命名
            lkyTableStorage.setAddress(uploadFolder);
            lkyTableStorage.setFileType(fileType);
            lkyTableStorage.setNewFileName(newFileName);
            //lkyTableStorage.setUid("32c0d596ee6d477cbee74b640c34972b");  // 默认是勿删老师1上传的
            //lkyTableStorage.setAdminFid("56d91203f3214264b8868597ea9e82f6");
            lkyTableStorage.setCreationTime(new Date());
            lkyTableStorage.setUpdateDate(new Date());
            lkyTableStorage.save();

            //老师发布表存储
            LkyTeacherReleaseRecord lkyTeacherReleaseRecord = new LkyTeacherReleaseRecord();
            String ffrId = UUID.randomUUID().toString().replace("-","");
            lkyTeacherReleaseRecord.setId(ffrId);
            lkyTeacherReleaseRecord.setFid(tsId);
            lkyTeacherReleaseRecord.save();
//            dicPopedom.setPopedomName("上传"+fileName+"成功");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            // 一、老师-学生表id；二、老师发布表id
            String ids=ffrId+"-"+tsId;
            System.out.println("+++++++++++++++++++++++++ids"+ids);
            return ids;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            dicPopedom.setPopedomName("上传"+fileName+"失败");
//            SoJLogKit.writeLog(this, dicPopedom,getSessionUser());
            return "上传失败";
        }
    }




    /**
     * 文件下载
     */
    @GetMapping("download")
    public String downLoad(HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
        File file = new File(uploadFolder + "/" + fileName);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }




}